import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from cookbook2.lib.base import BaseController, render
from cookbook2 import model

log = logging.getLogger(__name__)

class LoginController(BaseController):
    c.errlogin = ''
    c.errpass = ''
	
    def login(self):
        c.errlogin = ''
        c.errpass = ''
        form_username = str(request.params.get('login'))
        form_password = str(request.params.get('pass'))
        
        # Get user data from database
        q = model.Session.query(model.User)
        db_user = q.filter_by(login=form_username).first()
        #db_user = model.User.query(User).get_by(login=form_username)
        if db_user is None: # User does not exist
		    c.errlogin = 'Uzytkownik nie istnieje'
		    return render('/index.mako')
		    #return 

        # Wrong password? (http://pypi.python.org/pypi/py-bcrypt used here)
        #if db_user.passwd != bcrypt.hashpw(form_password, db_user.passwd):
        if form_password != db_user.password:
		    c.errpass = 'Bledne haslo'
		    return render('/index.mako')

        # Mark user as logged in
        session['user'] = form_username
        session.save()

		
        # Send user back to the page he originally wanted to get to
        if session.get('path_before_login'):
            redirect(session['path_before_login'])
        else: # if previous target is unknown just send the user to a welcome page
            return render('/index.mako')

    def logout(self):
        """Log out the user and display a confirmation message."""
        if 'user' in session:
            del session['user']
            session.save()
        return render('/index.mako')
		

        # Attach the object to the session.
        #model.Session.add(newuser)

        # Commit the transaction.
        #model.Session.commit()
        #return render('/register.mako')
        #redirect(url(controller="login", action="index"))
